function clearTopDiv() {
    let isTopDiv = document.getElementById('topDiv');
    if (isTopDiv != null || !isTopDiv == undefined) {
        document.body.removeChild(isTopDiv);
    }
}

var upColor = '#ec0000';
var upBorderColor = '#8A0000';
var downColor = '#00da3c';
var downBorderColor = '#008F28';

function splitData(rawData) {
    var categoryData = [];
    var values = []
    for (var i = 0; i < rawData.length; i++) {
        let date = rawData[i].splice(0, 1)[0]; //去除rawData数组的第一个日期元素，留下开盘价、收盘价、最高价、最低价
        values.push(rawData[i]);

        //和昨天收盘价的比率
        let rise = i === 0 ? 1 : (rawData[i][1] - rawData[i - 1][1]) / rawData[i - 1][1] * 100;
        let title = date + ' ' + rise.toFixed(2) + '%';
        categoryData.push(title); //显示日期、收盘价比率

    }
    return {
        categoryData: categoryData,
        values: values
    };
}

//计算一段时间的移动平均线
function calculateMA(dayCount, data) {
    var result = [];
    for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data.values[i - j][1];
        }
        result.push((sum / dayCount).toFixed(2));
    }
    return result;
}

// 生成K线图
function renderKChart(divId, title, data) {

    var isTopDiv = document.getElementById('topDiv');
    var topDiv;
    var chartDiv = document.createElement("div");
    chartDiv.id = divId;
    chartDiv.style.width = "100%";
    chartDiv.style.height = "500px";

    //没有顶层div则创建,有则追加进顶层div中
    if (isTopDiv == null || isTopDiv == undefined) {
        topDiv = document.createElement("div");
        topDiv.id = "topDiv";
        topDiv.appendChild(chartDiv);
        document.body.appendChild(topDiv);
    } else {
        isTopDiv.appendChild(chartDiv);
    }

    var myChart = echarts.init(document.getElementById(chartDiv.id));

    // 数据意义：开盘(open)，收盘(close)，最低(lowest)，最高(highest)
    var data0 = splitData(data);
    myChart.setOption(option = {

        title: {
            text: title,
            left: 0
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']
        },
        grid: {
            left: '10%',
            right: '10%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            data: data0.categoryData,
            scale: true,
            boundaryGap: false,
            axisLine: {onZero: false},
            splitLine: {show: false},
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax'
        },
        yAxis: {
            scale: true,
            splitArea: {
                show: true
            }
        },
        dataZoom: [
            {
                type: 'inside',
                start: 80,
                end: 100
            },
            {
                show: true,
                type: 'slider',
                top: '90%',
                start: 50,
                end: 100
            }
        ],
        series: [
            {
                name: '日K',
                type: 'candlestick',
                data: data0.values,
                itemStyle: {
                    color: upColor,
                    color0: downColor,
                    borderColor: upBorderColor,
                    borderColor0: downBorderColor
                },
                markPoint: {
                    label: {
                        normal: {
                            formatter: function (param) {
                                return param != null ? Math.round(param.value) : '';
                            }
                        }
                    },
                    data: [
                        {
                            name: 'XX标点',
                            coord: ['2013/5/31', 2300],
                            value: 2300,
                            itemStyle: {
                                color: 'rgb(41,60,85)'
                            }
                        },
                        {
                            name: 'highest value',
                            type: 'max',
                            valueDim: 'highest'
                        },
                        {
                            name: 'lowest value',
                            type: 'min',
                            valueDim: 'lowest'
                        },
                        {
                            name: 'average value on close',
                            type: 'average',
                            valueDim: 'close'
                        }
                    ],
                    tooltip: {
                        formatter: function (param) {
                            return param.name + '<br>' + (param.data.coord || '');
                        }
                    }
                },
                markLine: {
                    symbol: ['none', 'none'],
                    data: [
                        [
                            {
                                name: 'from lowest to highest',
                                type: 'min',
                                valueDim: 'lowest',
                                symbol: 'circle',
                                symbolSize: 10,
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                }
                            },
                            {
                                type: 'max',
                                valueDim: 'highest',
                                symbol: 'circle',
                                symbolSize: 10,
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                }
                            }
                        ],
                        {
                            name: 'min line on close',
                            type: 'min',
                            valueDim: 'close'
                        },
                        {
                            name: 'max line on close',
                            type: 'max',
                            valueDim: 'close'
                        }
                    ]
                }
            },
            {
                name: 'MA5',
                type: 'line',
                color: '#0f0f0f',
                data: calculateMA(5, data0),
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    opacity: 1,
                    color: '#0f0f0f'
                }
            },
            {
                name: 'MA10',
                type: 'line',
                color: '#e9b520',
                data: calculateMA(10, data0),
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    opacity: 0.5,
                    color: '#e9b520'
                }
            },
            {
                name: 'MA20',
                type: 'line',
                color: '#df7474',
                data: calculateMA(20, data0),
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    opacity: 0.5,
                    color: '#df7474'
                }
            },
            {
                name: 'MA30',
                type: 'line',
                color: '#65d567',
                data: calculateMA(30, data0),
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    opacity: 0.5,
                    color: '#65d567'
                }
            },

        ]
    });
}

/*每次根据基金code生成一条折线图,多条则循环调用*/
function renderChart(divId, title, data, maxValue, minValue) {

    if (minValue == null || maxValue == undefined) {
        minValue = 1;
        maxValue = 100;
    }

    var isTopDiv = document.getElementById('topDiv');
    var topDiv;
    var chartDiv = document.createElement("div");
    chartDiv.id = divId;
    chartDiv.style.width = "100%";
    chartDiv.style.height = "220px";

    //没有顶层div则创建,有则追加进顶层div中
    if (isTopDiv == null || isTopDiv == undefined) {
        topDiv = document.createElement("div");
        topDiv.id = "topDiv";
        topDiv.appendChild(chartDiv);
        document.body.appendChild(topDiv);
    } else {
        isTopDiv.appendChild(chartDiv);
    }

    var myChart = echarts.init(document.getElementById(chartDiv.id));
    myChart.setOption(option = {
        title: {
            text: title
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            data: data.map(function (item) {
                return item[0];
            })
        },
        yAxis: {
            splitLine: {
                show: false
            },
            min: function (value) {
                var m = value.min;

                if (m > 1 && m < 10) {
                    m = (m - 1).toFixed(1);
                } else {
                    m = (m - 5).toFixed(1);
                }
                return m;
            }
        },
        toolbox: {
            left: 'center',
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                restore: {},
                saveAsImage: {}
            }
        },
        dataZoom: [{
            startValue: '2014-06-01'
        }, {
            type: 'inside'
        }],
        visualMap: {
            top: 10,
            right: 10,
            precision: 1,
            pieces: [{
                gt: 1,
                lte: minValue,
                color: '#096'
            }, {
                gt: minValue,
                lte: (maxValue + minValue) / 2,
                color: '#ff9933'
            }, {
                gt: (maxValue + minValue) / 2,
                lte: maxValue,
                color: 'red'
            }, {
                gt: maxValue,
                color: '#7e0023'
            }],
            outOfRange: {
                color: '#999'
            }
        },
        series: {
            name: title,
            type: 'line',
            data: data.map(function (item) {
                return item[1];
            }),
            markLine: {
                silent: true,
                data: [{
                    yAxis: minValue
                }, {
                    yAxis: minValue + (maxValue - minValue) / 3
                }, {
                    yAxis: minValue + (maxValue - minValue) * 2 / 3
                }, {
                    yAxis: maxValue
                }]
            }
        }
    });
}
